package com.edu.controller.front.pay;

import com.edu.entity.AlipayBean;
import com.edu.entity.Order;
import com.edu.service.ordertab.OrderService;
import com.edu.service.ordertab.OrderServiceImpl;
import com.edu.utils.AliPayUtil;
import com.edu.utils.ParamFormat;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigInteger;

/**
 * @author ZCN
 * @version 1.0
 * @date 2021/11/24 15:55
 */
@WebServlet("/front/alipay")
public class AliPayServlet extends HttpServlet {
    private OrderService orderService = new OrderServiceImpl();
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        try {
            ParamFormat.format(req, resp);
            Integer id = Integer.valueOf(req.getParameter("id"));
            Order order = orderService.selectByid(BigInteger.valueOf(Long.valueOf(id.toString())));

            AlipayBean alipayBean = new AlipayBean();
            // 订单号
            alipayBean.setOut_trade_no(order.getOrdersn());
            // 订单名称
            alipayBean.setSubject(order.getOrdername());
            // 付款金额
            alipayBean.setTotal_amount(Double.valueOf(order.getPrice().toString()));
            // 产品码
            alipayBean.setProduct_code("FAST_INSTANT_TRADE_PAY");

            String form = AliPayUtil.connect(alipayBean);

            // 对支付宝返回信息封装
            String s = form.replaceAll("\r|\n", "");
            int i = s.indexOf("</script>");
            StringBuffer stringBuffer = new StringBuffer(s);
            String s1 = stringBuffer.insert(i + 1, "\\").toString();

            req.setAttribute("form",s1);
            req.getRequestDispatcher("/front/pay.jsp").forward(req,resp);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
